Ext.BLANK_IMAGE_URL = 'javascripts/ext-2.0.2/resources/images/default/s.gif';
Ext.timeoutInterval = 2000;

function loadStoreForCase(val) {
	Ext.task_grid.show();
	Ext.overview_grid.hide();
	Ext.current_case = val;
	Ext.task_grid.loadMask.msg = "Loading tasks for Case #"+val+"...";							
	
	Ext.store2.proxy.conn.url = '/cases/' + val;	
	Ext.store2.reload();
	Ext.getCmp('top-panel').setTitle('Case List for Case #' + val);
	Ext.task_grid.render();
	
	setTimeout("Ext.task_grid.selModel.selectFirstRow();taskOnClick();", Ext.timeoutInterval);
}

function loadMonitoringGrid() {
	Ext.task_grid.hide();
	Ext.getCmp('top-panel').setTitle('Monitoring');
	Ext.overview_grid.show();
	Ext.overview_grid.loadMask.msg = 'Loading Monitoring information';
	Ext.store_overview.reload();
	Ext.overview_grid.render();
}


function submitOnLoad() {
	var clickevent = document.createEvent("UIEvents");
	clickevent.initEvent("DOMActivate", "true", "true");	
	form_frame.document.getElementById('submit-trigger').dispatchEvent(clickevent);
	Ext.get(document.body).unmask();
	taskOnClick();	
}

Ext.submitOnLoad = submitOnLoad;

function spawnProcess(transition_id) {
	Ext.get(document.body).mask("Spawning process...");
	var conn = new Ext.data.Connection();
	conn.request({url: String.format('/transitions/{0}/tokens', transition_id), method:'POST'});
	setTimeout("Ext.get(document.body).unmask();Ext.store.reload();Ext.case_grid.render();", Ext.timeoutInterval);
}

function onFormFrameLoad() {
	if (Ext.current_case > 0) {
	Ext.task_grid.loadMask.msg = "Loading tasks for Case #"+Ext.current_case +"...";							
	
	Ext.store2.proxy.conn.url = '/cases/' + Ext.current_case;	
	Ext.store2.reload();
	Ext.getCmp('top-panel').setTitle('Case List for Case #' + Ext.current_case);
	Ext.task_grid.render();
	}
}

function taskOnClick(blub) {
	Ext.spawnBtn.setDisabled(true);
	Ext.allocateBtn.setDisabled(true);
	Ext.submitBtn.setDisabled(true);
	Ext.suspendBtn.setDisabled(true);
	Ext.resumeBtn.setDisabled(true);
	Ext.delegateBtn.setDisabled(true);
	Ext.reviewBtn.setDisabled(true);
	Ext.skipBtn.setDisabled(true);
	

	if (Ext.task_grid.selModel.getSelected() != null) {

	Ext.task_grid.loadMask.msg = "Loading actions for selected task...";							
	Ext.task_grid.loadMask.show();
	Ext.actionsStore = new Ext.data.Store({
	    url: '/cases/'+Ext.task_grid.selModel.getSelected().data.case_id,
	    reader: new Ext.data.XmlReader({
	           record: 'task',
	           id: 'transition_id',
	           totalRecords: '@total'
	       }, [
	           'action', 'transition_name', 'transition_id'
	       ])
	});
	
	Ext.actionsStore.on('load', function(a,b,c) {
		Ext.actionsStore.each(function(rec) {
		if (Ext.task_grid.selModel.getSelected().data.transition_name == rec.data.transition_name && Ext.task_grid.selModel.getSelected().data.user_enabled != "false") {
			switch (rec.data.action)
				{
				case 'allocate':
				  Ext.allocateBtn.transition_id = rec.data.transition_id;
				  Ext.allocateBtn.setDisabled(false);
				
				// only if allocate is the only action to do 
//					if (Ext.actionsStore.data.length == 1) {
//				  		Ext.get(document.body).mask("Allocating task...");
				  		form_frame.location = '/transitions/' + rec.data.transition_id;
//				  		setTimeout("Ext.submitOnLoad()", Ext.timeoutInterval);
//					}

				  break
				case 'submit':
				  Ext.submitBtn.transition_id = rec.data.transition_id;
				  Ext.submitBtn.setDisabled(false);
				  form_frame.location = '/transitions/' + rec.data.transition_id;
				  break
				case 'suspend':
				  Ext.suspendBtn.transition_id = rec.data.transition_id;
				  Ext.suspendBtn.setDisabled(false);
				  break
				case 'resume':
				  Ext.resumeBtn.transition_id = rec.data.transition_id;
				  Ext.resumeBtn.setDisabled(false);
				  form_frame.location = '/transitions/' + rec.data.transition_id;
				  break
				case 'delegate':
				  Ext.delegateBtn.transition_id = rec.data.transition_id;
				  Ext.delegateBtn.setDisabled(false);
				  break
				case 'review':
				  Ext.reviewBtn.transition_id = rec.data.transition_id;
				  Ext.reviewBtn.setDisabled(false);
				  break
				case 'skip':
				  Ext.skipBtn.transition_id = rec.data.transition_id;
				  Ext.skipBtn.setDisabled(false);
				  break
				case '':
				  Ext.spawnBtn.transition_id = rec.data.transition_id;
				  Ext.spawnBtn.setDisabled(false);
				  break
				  }
			}
			
		});
		
		Ext.task_grid.loadMask.hide();
		
	}, this);
	
	Ext.actionsStore.load();
	}
}



function buttonOnClick(blub) {
	form_frame.location = '/transitions/' + this.transition_id;
	
//	Ext.activated_button = this.text;
	
	if (this.text == 'allocate') {
		Ext.get(document.body).mask("Allocating task...");
		setTimeout("Ext.submitOnLoad()", Ext.timeoutInterval);
	} else if (this.text == 'skip') {
		Ext.get(document.body).mask("Skipping task...");
		setTimeout("Ext.submitOnLoad()", Ext.timeoutInterval);
	} else if (this.text == 'resume') {
		Ext.get(document.body).mask("Resuming task...");
		setTimeout("Ext.submitOnLoad()", Ext.timeoutInterval);
	} else if (this.text == 'suspend') {
		Ext.get(document.body).mask("Suspending task...");
		setTimeout("Ext.submitOnLoad()", Ext.timeoutInterval);
	}	
}

Ext.onReady(function() {

Ext.button_toolbar = new Ext.Toolbar({width:'100%', height:'100%', autoFit: true});

Ext.store = new Ext.data.Store({
    url: '/cases',

    reader: new Ext.data.XmlReader({
           record: 'task',
           id: 'case_id',
           totalRecords: '@total'
       }, [
           'case_id' , 'net_name'        
       ])
});

Ext.store2 = new Ext.data.GroupingStore({
    url: '/cases/1',
	groupField: 'transition_name',
	sortInfo: {field: 'transition_name', direction: 'ASC'},
    reader: new Ext.data.XmlReader({
           record: 'task',
           id: 'transition_name',
           totalRecords: '@total'
       }, [
           'transition_id', 'transition_name' , 'action', 'case_id', 'pending_time', 'role', 'delegation_ratio', 'user_enabled'
       ])
});

Ext.store3 = new Ext.data.GroupingStore({
    url: '/cases/0',
	groupField: 'transition_id',
	sortInfo: {field: 'transition_id', direction: 'ASC'},
    reader: new Ext.data.XmlReader({
           record: 'task',
           id: 'transition_id',
           totalRecords: '@total'
       }, [
           'transition_id', 'net_name'
       ])
});

Ext.store_overview	 = new Ext.data.GroupingStore({
    url: '/overview',
	groupField: 'net_id',
	sortInfo: {field: 'case_id', direction: 'ASC'},
    reader: new Ext.data.XmlReader({
           record: 'instance',
           id: 'case_id',
           totalRecords: '@total'
       }, [
           'net_id', 'case_id', 'transition_count', 'duration', 'involved_users_count', 'adhoc_order'
       ])
});

Ext.overview_grid = new Ext.grid.GridPanel({
        store: Ext.store_overview,
        columns: [
            {id:'case_id',header: "case_id", sortable: true, dataIndex: 'case_id'},
            {header: "net_id", dataIndex: 'net_id'},
            {header: "transition_count", dataIndex: 'transition_count'},
            {header: "duration", dataIndex: 'duration', renderer: pendingTimeRenderer},
            {header: "involved_users_count", dataIndex: 'involved_users_count'},
            {header: "adhoc_order", dataIndex: 'adhoc_order'},
        ],

        view: new Ext.grid.GroupingView({
            forceFit:true,
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
        }),

        frame:true,
        height: 220,
        width: '100%',
        collapsible: true,
        animCollapse: false,
		hidden: true,
//        title: 'Monitoring',
        iconCls: 'icon-grid'
    });

Ext.case_grid = new Ext.grid.GridPanel({
	        store: Ext.store,
	        columns: [
	            {header: "case_id", dataIndex: 'case_id', sortable: true, renderer: caseLinkRenderer},
	            {header: "name", dataIndex: 'net_name', sortable: true}
	        ],
	        width: '100%',
	        height: 400,
	        loadMask : {msg:"Loading cases..."},
        	viewConfig: {
					        forceFit: true,
					        autoFit: true
					    }
	        });
		
Ext.task_grid = new Ext.grid.GridPanel({
	store: Ext.store2,							
	columns: [ 
//	{id: 'transition_id', header: 'transition id', sortable: true, dataIndex: 'transition_id', renderer: transitionLinkRenderer},
		{header: 'task name', sortable: true, dataIndex: 'transition_name'},
//	{header: 'attractivity', sortable: true, dataIndex: 'attractivity', renderer: attractivityRenderer},
		{header: 'active since', sortable: true, dataIndex: 'pending_time', renderer: pendingTimeRenderer},
		{header: 'delegation ratio', sortable: true, dataIndex: 'delegation_ratio', renderer: delegationRenderer},
		{header: 'role', sortable: true, dataIndex: 'role'}
//	, {header: 'action', sortable: true, dataIndex: 'action'}
	],
        view: new Ext.grid.GridView({
            forceFit:true
        }),
	loadMask : {msg:"Loading tasks..."},							
        frame:true,
        height: 220,
        width: '100%',
        collapsible: true,
        animCollapse: false,
	onClick: taskOnClick
});				        



Ext.spawn_grid = new Ext.grid.GridPanel({
		        store: Ext.store3,
		        columns: [
		            {header: "id", dataIndex: 'transition_id', sortable: true, renderer: spawnLinkRenderer},
		            {header: "name", dataIndex: 'net_name', sortable: true}
		        ],
		        width: '100%',
		        height: 400,
		        loadMask : {msg:"Loading deployed petrinets..."},
                	viewConfig: {
						        forceFit: true,
						        autoFit:true
						    }
		        });

// --- renderer ------------------------------------------------

function transitionLinkRenderer(value){
	return String.format('<a href="/transitions/{0}" target="form_frame">DO</a>', value);
}

function spawnLinkRenderer(value){
	return String.format('<a href="javascript:spawnProcess({0})">{0}</a>', value);
}

function caseLinkRenderer(value) {
	return String.format('<a href="javascript:loadStoreForCase({0})">{0}</a>', value); 
}

function floattorgb(val) {
	return parseInt(parseFloat(val)*2.55);
}

function delegationRenderer(value) {
	value = parseFloat(value)*100;
	output = '' + value + ' %';
	if (value > 40)	{
		output = '<span style="color: rgb(255,0,0);">' + output + '</span>';
	}
	return output;
}

function pendingTimeRenderer(value) {
	var output = "";
	if (value > 86400) { // Days
		var days = Math.floor(value / 86400);
		var hours = Math.floor((value - (days * 86400)) / 3600);
		output = "" + days + "d " + hours + "h";
	} else if (value > 3600) { // hours
		var hours = Math.floor(value / 3600);
		var minutes = Math.floor((value - (hours * 3600)) / 60);
		output = "" + hours + "h " + minutes +"m";
	} else if (value > 60) { //minutes
		var minutes = Math.floor(value / 60);
		var seconds = Math.floor(value - (minutes * 60));
		output = "" + minutes + "min " + seconds +"sec";
	} else {
		var seconds = Math.floor(value);
		output = "" + seconds +"sec";		
	}
	
	return output;
}


// --------------------------------------------------------------

/*
function attractivityRenderer(value) {
	return '<span style="color: rgb(' + (255 - floattorgb(value)) + ','+floattorgb(value)+', 0);">' + value + '</span>'; 
}
*/


Ext.viewport = new Ext.Viewport({
            layout:'border',
            items:[{
                region:'west',
                id:'west-panel',
                title:'Navigation',
                split:true,
                width: 200,
                minSize: 175,
                maxSize: 400,
                collapsible: true,
                layout:'accordion',
                layoutConfig:{
                    animate:true
                },
                items: [  {
			                region:'west1',
			                id:'west1-panel',
			                title:'Cases',
			                split:true,
			                collapsible: true,
			                autoScroll: true,
			                margins:'35 0 5 5',
			                cmargins:'35 5 5 5',
			                width: '100%',
			                height: '100%',			                
			                buttons: [
			                	new Ext.Button({id: 'reload_cases', text: 'Reload', onClick: function() {
			                		Ext.store.reload();
							Ext.case_grid.render();
			                	}})
			                ],
			                items: Ext.case_grid
			                },{
			                region:'west2',
			                id:'west2-panel',
			                title:'Monitoring & Analysis',
			                split:true,
			                collapsible: true,
			                margins:'35 0 5 5',
			                cmargins:'35 5 5 5',
			                layout:'accordion',
			                layoutConfig:{
			                    animate:true
			                },
			                html: '<ul><li><div class="x-panel-header x-unselectable x-panel-icon icon-grid" style="background: none"><a href="javascript:loadMonitoringGrid()">Monitoring-Overview</a></div></li></ul>'
			                },
/*					{
			                region:'west3',
			                id:'west3-panel',
			                title:'User Management',
			                split:true,
			                collapsible: true,
			                margins:'35 0 5 5',
			                cmargins:'35 5 5 5',
			                layout:'accordion',
			                layoutConfig:{
			                    animate:true
			                }
			                },
*/
			                {
			                region:'west4',
			                id:'west4-panel',
			                title:'Spawn Processes',
			                split:true,
			                collapsible: true,
			                margins:'35 0 5 5',
			                cmargins:'35 5 5 5',
			                width: '100%',
			                height: '100%',			                
			                buttons: [
			                	new Ext.Button({id: 'reload_spawns', text: 'Reload', onClick: function() {
			                		Ext.store3.reload();
							Ext.spawn_grid.render();				                	
				                	}
						})
			                ],
			                items: Ext.spawn_grid
			                }
			               ]
                
                },
                {
                layout:'column',
                region:'center',
                items: [  {
					layout: 'fit',
			                region:'top',
			                id:'top-panel',
			                title:'Case List',
			                split:false,
			                height: 250,
                                        width: '100%',
			                fitContainer:true,
					autoScroll: true,
			                collapsible: true,
			                margins:'35 0 5 5',
			                cmargins:'35 5 5 5',
			                items: [ Ext.task_grid , Ext.overview_grid ]
			                },
			                {
								layout: 'fit',
			                region:'button_toolbar',
			                id:'toolbar-panel',
			                split:false,
			                height:30,
			                width: '100%',
			                margins:'35 0 5 5',
			                cmargins:'35 5 5 5',
			                items: Ext.button_toolbar
			                },
			                {
							layout: 'fit',
			                region:'bottom',
			                id:'bottom-panel',
			                title:'Task Execution',
			                split:false,
			                width: '100%',
//							height: '100%',
			                margins:'35 5 5 5',
			                cmargins:'35 5 5 5',
							fitContainer:true,
							autoScroll: true,
							html: '<iframe style="border: 0px;" height="400" width="100%" id="form_frame" name="form_frame" src="about:blank" scrolling="auto" onload="javascript:onFormFrameLoad()"/>'
			                }
                ]
                }]
                
        });
        
        Ext.store.load();        
        Ext.store2.load();
        Ext.store3.load();
        Ext.store_overview.load();
        
        Ext.spawnBtn = new Ext.Button({id: 'spawn', text: 'default-action', onClick: buttonOnClick, disabled: true});
        Ext.allocateBtn = new Ext.Button({id: 'allocate', text: 'allocate', onClick: buttonOnClick, disabled: true});
        Ext.submitBtn = new Ext.Button({id: 'submit', text: 'submit', onClick: buttonOnClick, disabled: true});
        Ext.suspendBtn = new Ext.Button({id: 'suspend', text: 'suspend', onClick: buttonOnClick, disabled: true});
        Ext.resumeBtn = new Ext.Button({id: 'resume', text: 'resume', onClick: buttonOnClick, disabled: true});
        Ext.delegateBtn = new Ext.Button({id: 'delegate', text: 'delegate', onClick: buttonOnClick, disabled: true});
        Ext.reviewBtn = new Ext.Button({id: 'review', text: 'review', onClick: buttonOnClick, disabled: true});
        Ext.skipBtn = new Ext.Button({id: 'skip', text: 'skip', onClick: buttonOnClick, disabled: true});
        
        Ext.button_toolbar.add(Ext.spawnBtn);
        Ext.button_toolbar.add(Ext.allocateBtn);
        Ext.button_toolbar.add(Ext.submitBtn);
        Ext.button_toolbar.add(Ext.suspendBtn);
        Ext.button_toolbar.add(Ext.resumeBtn);
        Ext.button_toolbar.add(Ext.delegateBtn);
        Ext.button_toolbar.add(Ext.reviewBtn);
        Ext.button_toolbar.add(Ext.skipBtn);

	setTimeout("Ext.viewport.doLayout();", Ext.timeoutInterval);
});
